package com.xpec.c4.db.log;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xpec.c4.db.basic.BasicBusunessDAO;
import com.xpec.c4.db.model.log.basic.BasicLogModel;

public class SaveBusinessLogTask implements Runnable {

	private Log log = LogFactory.getLog(SaveBusinessLogTask.class);
	/**
	 * 定时存储时一次批量可存储的日志个数
	 */
	private static int saveNum = LogPoolConstants.SAVE_NUM;

	@Override
	public void run() {
		try{
			int len = LogBusinessModelPool.getPoolSize();
			if (len != 0) {
				log.info(System.currentTimeMillis() + " save logs begin!");
				List<BasicLogModel> saveLogs = new ArrayList<BasicLogModel>();
				List<BasicLogModel> partOfSaveLogs = new ArrayList<BasicLogModel>();
	
				for (int i = 0; i < len; i++) {
					saveLogs.add(LogBusinessModelPool.poll());
				}
				int i = 0;
				for (BasicLogModel ilog : saveLogs) {
					if (ilog != null) {
						partOfSaveLogs.add(ilog);
					}
					i++;
	
					if (i % saveNum == 0 || i == saveLogs.size()) {
						if (!BasicBusunessDAO.saveLogs(partOfSaveLogs)) {
							for (BasicLogModel slog : partOfSaveLogs) {
								if (!BasicBusunessDAO.saveTransaction(slog)) {
									log.error("save log " + slog.getClass() + " " + slog
											+ " failed!");
								}
							}
							partOfSaveLogs.clear();
						} else {
							log.info("Logs Caculation:" + saveLogs.size()
									+ " Log had been saved successfully!");
							partOfSaveLogs.clear();
	
						}
					}
				}
	
				log.info(System.currentTimeMillis() + " save complete!");
			}
		}
		catch(Exception e){
			e.printStackTrace();
			log.info(System.currentTimeMillis() + " save business log error!");		
		}
	}
}
